package com.yue.modbus.service.impl;

import com.alibaba.excel.EasyExcel;
import com.yue.modbus.client.ModbusClient;
import com.yue.modbus.domain.Device;
import com.yue.modbus.listener.ExcelListener;
import com.yue.modbus.service.ReadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
@Qualifier("modbusReadServiceImpl")
@Slf4j
public class ModbusReadServiceImpl implements ReadService {
    @Value("${modbus.ip}")
    private String ip;
    @Value("${modbus.port}")
    private String port;
    @Value("${modbus.table}")
    private String excelTable;
    private final CopyOnWriteArrayList<String> alarmSet = new CopyOnWriteArrayList<>();
    private Boolean firstFlag = true;
    public void read() {
        log.info("ModBusClient start");
        List<Device> modbusConfig = getModbusConfig();
        ModbusClient modbusClient = new ModbusClient(ip, Integer.parseInt(port));
        modbusClient.setModbusConfig(modbusConfig);
        // 开机第一次接到的消息如果需要报警的则不用报警

        modbusClient.setMsgCallBack(list -> {
            list.stream().forEach(item -> {
                if (item.getCurValue() && !item.getPreValue() && !firstFlag) {
                    log.info("add alarm point：" + item.getDevice()+" " + item.getPoint());
                    alarmSet.add(item.getPoint());
                }
            });
            firstFlag = false;
        });
        modbusClient.connect();
    }

    @Override
    public void write() {

    }

    private List<Device> getModbusConfig(){
        ExcelListener r =new ExcelListener();
        EasyExcel.read(excelTable, Device.class,r).sheet().doRead();
        return r.getData();
    }

    public CopyOnWriteArrayList<String> getAlarmSet() {
        return alarmSet;
    }
}
